package com.lianjia.sh.se.message.event.client.listener;

import com.alibaba.fastjson.JSONObject;
import com.lianjia.sh.se.kafka.client.AbstractKafkaListener;
import com.lianjia.sh.se.message.event.client.model.MessageEvent;
import com.lianjia.sh.se.message.event.client.publisher.MessageEventPublisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by yangsp1 on 16/8/3.
 */
public abstract class AbstractMessageEventListener extends AbstractKafkaListener{
    Logger logger = LoggerFactory.getLogger(AbstractMessageEventListener.class);

    @Autowired
    MessageEventPublisher messageEventPublisher;

    @Override
    public void onMessage(String message) {
        MessageEvent messageEvent = JSONObject.parseObject(message,MessageEvent.class);
        try {
            onMessage(messageEvent);
        }catch (Exception e){
            //发送失败时，记录日志（仍然以event方式发送到kafka)
            try {
                MessageEvent messageEventError = new MessageEvent();
                messageEventError.setData(message);
                messageEventError.setProjectCode("messageEventLog");
                messageEventError.setServiceCode("error");
                messageEventPublisher.publishEvent(messageEventError);
            }catch (Exception e1) {
                logger.error(e1.getMessage(),e1);
            }
            throw e;
        }
    }

    /**
     * 子类实现
     * @param messageEvent
     */
    public abstract void onMessage(MessageEvent messageEvent);
}
